package cm367;

import javax.faces.application.Application;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class CheckLoginPhaseListener implements PhaseListener{

	private static final long serialVersionUID = 1L;

	@Override
	public void afterPhase(PhaseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void beforePhase(PhaseEvent arg0) {
		FacesContext context = FacesContext.getCurrentInstance();
		System.out.println("View Id: "+context.getViewRoot().getViewId());
		if (context.getViewRoot().getViewId().equals("/user/ok.xhtml") ||
				context.getViewRoot().getViewId().equals("/user/set.xhtml") ||
				context.getViewRoot().getViewId().equals("/facilities/edFacilities.xhtml")||
				context.getViewRoot().getViewId().equals("/facilities/SaveFacility.xhtml")||
				context.getViewRoot().getViewId().equals("/booking/bookingdetail.xhtml")||
				context.getViewRoot().getViewId().equals("/booking/bookingReceipt.xhtml") ||
				context.getViewRoot().getViewId().equals("/venue/modify.xhtml")
				){
			Application app = context.getApplication();
			LoggedInUser loggedInUser = app.evaluateExpressionGet(context, "#{loggedInUser}", LoggedInUser.class);
			if (loggedInUser.getUser() == null){
				loggedInUser.setOriginalViewId(context.getViewRoot().getViewId());
				ViewHandler viewHandler = app.getViewHandler();
				UIViewRoot viewRoot = viewHandler.createView(context, "/user/login.xhtml");
				context.setViewRoot(viewRoot);
			} else 
				if (loggedInUser.getUser().getRole().equals("user") 
					&& (context.getViewRoot().getViewId().equals("/user/set.xhtml") ||
						context.getViewRoot().getViewId().equals("/facilities/edFacilities.xhtml") ||
						context.getViewRoot().getViewId().equals("/facilities/SaveFacility.xhtml") ||
						context.getViewRoot().getViewId().equals("/venue/modify.xhtml"))) {
					ExternalContext externalContext = context.getExternalContext();
					Object session = externalContext.getSession(false);
					HttpSession httpSession = (HttpSession) session;
					httpSession.invalidate();
			}
		}
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

}
